import {BaseSession} from "./base";
import {fromAny, toAny, StringValue, BoolValue} from "../proto"

class FileSession extends BaseSession {
    private fileName: string

    constructor(render: HTMLElement) {
        super('File', render);
    }

    onCreate(sessionId: number, futureId: number, ...argv) {
        super.onCreate(sessionId, futureId, ...argv);
    }

    onDestroy() {
        super.onDestroy();
    }

    async onReceive(name: String, sessionId: number, futureId: number, ...argv) {
        switch (name) {
            case "open":
                await this.open(...argv);
                return;
            case "read":
                await this.read(sessionId, futureId);
                return;
            case "readLine":
                await this.readLine(sessionId, futureId);
                return;
            case "write":
                await this.write(...argv);
                return;
            case "exists":
                await this.exists(sessionId, futureId);
                return;
            case "remove":
                await this.remove();
                return;
            default:
                super.onReceive(name, sessionId, futureId, ...argv);
                return;
        }
    }

    async open(...argv) {
        this.fileName = fromAny(argv[0], StringValue).replace(".", "_");
    }

    async  read(sessionId, futureId){
        const data = localStorage.getItem(this.fileName)
        console.log('data: ->')
        console.log(data)
        this.sendAction("onRead", sessionId, futureId, toAny(data, StringValue))
    }

    async readLine(_sessionId, _futureId) {}

    async write(...argv) {
        const content = fromAny(argv[0], StringValue);
        localStorage.setItem(this.fileName, content);

        const data = localStorage.getItem(this.fileName)
        console.log('data: w->')
        console.log(data)
    }

    async exists(sessionId, futureId) {
        const res = !!localStorage.getItem(this.fileName)
        this.sendAction("onExists", sessionId, futureId, toAny(res, BoolValue))
    }

    async remove() {
        localStorage.removeItem(this.fileName);
    }
}

export { FileSession }